<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 11:18
 */

namespace Modules\SmallApi\Service;

use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\GoodsCateRepository;
// use HiCommon\Repository\GoodsSpecsRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\CouponsRepository;
use HiCommon\Repository\RepairstoreGoodsRepository;

class GoodsService extends BaseService
{

    /**
     *    积分兑换列表
     *    hinq 2019 09 03
     *    使用场景【个人中心 积分兑换】
     **/
    public function get_list_limit()
    {

        try {
            //获取当前用户的可用积分
            $arr_where['field'] = ['id', 'integral'];
            $arr_user_info = UsersRepository::get_one((int)small_api_user_id(), (array)$arr_where);

            //获取商品分类
            $arr_type = GoodsCateRepository::get_cate_list((array)['pid' => 0, 'status' => 1, 'type' => 2]);
            $temp = [];
            $where['status'] = 1;
            $where['type'] = 2;
            foreach ($arr_type as $key => $value) {
                $where['cate_id'] = $value['id'];
                $arr_tuijian[$key]['type'] = $value['id'];
                $arr_tuijian[$key]['title'] = $value['name'];

                $info = GoodsRepository::get_list_where_limit((array)$where, 3, ['id', 'pic_url', 'name', 'title', 'integral'])->toarray();

                foreach ($info as $k => &$val) {
                    $integral = array_column($val['product_info'], 'integral');
                    $val['integral'] = min($integral) ?? 0;
                }
                $arr_tuijian[$key]['data'] = $info;
                if (count($arr_tuijian[$key]['data']) == 0) {
                    unset($arr_tuijian[$key]);
                }
            }

            $temp['user'] = $arr_user_info;
            $temp['goods_list'] = $arr_tuijian;

            return ['state' => 0, 'msg' => 'ok', 'data' => $temp, 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    获取更多指定类型的商品
     *    hinq 2019 09 03
     *    使用场景 【 个人中心  积分兑换 更多】
     **/
    public function get_goods_more(array $arrInput)
    {
        try {

            $cate_id = !empty($arrInput['cate_id']) ? intval($arrInput['cate_id']) : 1;
            $arr_where['where'] = ['cate_id' => $cate_id, 'status' => 1, 'type' => 2];
            $arr_where['field'] = ['id', 'name', 'title', 'pic_url', 'price', 'integral', 'sell'];
            $arr_where['with'] = ['product_info'];

            $res = GoodsRepository::get_list((array)$arr_where)->toArray();

            foreach ($res['data'] as $k => &$val) {
                $price = array_column($val['product_info'], 'price');
                $integral = array_column($val['product_info'], 'integral');

                $val['price'] = number_format_money(min($price) ?? 0.00);
                $val['integral'] = min($integral) ?? 0;
            }

            $result = hi_check_res($res, 'get_one');
            if ($result['state'] != 0) {
                return ['state' => 1, 'msg' => '数据获取失败', 'data' => [], 'error' => ''];
            }

            $temp['data'] = $res['data'];
            $temp['page'] = [
                "current_page" => $res['current_page'],
                "per_page" => $res['per_page'],
                "last_page" => $res['last_page'],
                "total" => $res['total']
            ];

            return ['state' => 0, 'msg' => 'ok', 'data' => $temp, 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     *    获取指定商品详情
     *    hinq 2019 09 03
     *    使用场景 【个人中心 积分兑换 详情】
     **/
    public function get_detail_goods(int $nId)
    {
        try {
            if (empty($nId)) {
                return ['state' => 1, 'msg' => '参数不能为空', 'data' => [], 'error' => ''];
            }
            //获取商品的主表信息
            $arr_option['with'] = ['img', 'product_info', 'sale_tag_relation' => function ($query) {
                $query->with(['sale_tag']);
            }];
            $res = GoodsRepository::get_one((int)$nId, (array)$arr_option)->toArray();
            $is_collect = false;
            if (!empty(small_api_user_id())) {
                $arr_where = ['x_id' => $nId, 'user_id' => small_api_user_id(), 'type' => 1];
                $count = CollectRepository::get_count_by_where((array)$arr_where);
                if ($count > 0) {
                    $is_collect = true;
                }
            }
            $res['is_collect'] = $is_collect;
            $result = hi_check_res($res, 'get_one');
            if ($result['state'] != 0) {
                return ['state' => 1, 'msg' => '数据获取失败', 'data' => [], 'error' => ''];
            }
            $http = env('API_HOST', 'https://xdminiapi.chxing.cn');
            if (stripos($res['detail'], '<img src="/')) {
                $res['detail'] = str_replace('src="/', 'src="' . $http . '/', $res['detail']);
                $res['detail'] = str_replace('/>', ' align="center" width="100%"/>', $res['detail']);
            }

            $min = reset($res['product_info'])['integral'];//最小积分
            $max = end($res['product_info'])['integral'];//最大积分
            if ($min == $max) {
                $res['integral'] = $min;
            } else {
                $res['integral'] = $min . '-' . $max;
            }
            $res['sale_tag_relation'] = array_column($res['sale_tag_relation'], 'sale_tag');

            return ['state' => 0, 'msg' => 'ok', 'data' => $res, 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

    /**
     * 获取商品规格属性
     */
    public function get_goods_specs(int $nId)
    {
        try {
            if (empty($nId)) {
                return ['state' => 1, 'msg' => '参数不能为空', 'data' => [], 'error' => ''];
            }
            $where = ['goods_id' => $nId];
            $res = GoodsProductRepository::get_list_where($where);
            $infor = array();
            foreach ($res as $key => $item) {
                $infor['specsCate'] = $item['specs']['specs_cate']['name'];
                $infor['specs'][] = [
                    'specs_id' => $item['specs']['id'],
                    'specs_name' => $item['specs']['name'],
                    'goods_id' => $item['goods_id'],
                    'product_id' => $item['id'],
                    'integral' => $item['integral'],
                    'price' => $item['price'],
                    'stock' => $item['stock'],
                    'pic' => $item['pic'],
                ];
            }

            $result = hi_check_res($infor, 'get_one');
            if ($result['state'] != 0) {
                return ['state' => 1, 'msg' => '数据获取失败', 'data' => [], 'error' => ''];
            }

            return ['state' => 0, 'msg' => 'ok', 'data' => $infor, 'error' => ''];
        } catch (\Exception $exception) {
            return ['state' => 1, 'msg' => $exception->getMessage()];
        }
    }

}